/*
 * The MIT License
 *
 * Copyright (c) 2013-2016 reark project contributors
 *
 * https://github.com/reark/reark/graphs/contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.reark.rxgithubapp.advanced.widget;

import io.reark.rxgithubapp.ResourceTable;
import io.reark.rxgithubapp.advanced.data.DbUtils;
import io.reark.rxgithubapp.advanced.data.UserSettings;
import io.reark.rxgithubapp.shared.network.NetworkApi;
import ohos.agp.components.ComponentProvider;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import okhttp3.*;

import java.io.*;
import java.util.concurrent.TimeUnit;

public class WidgetProvider {
    static Context mContext;
    //    static Image image;
    static ComponentProvider componentProvider;
    private static final String FORMAT = "image/jpeg";

    public static ComponentProvider getComponentProvider(Context context) {
        mContext = context;
        int layoutId = ResourceTable.Layout_widget_layout;
        componentProvider = new ComponentProvider(layoutId, context);
        UserSettings userSettings = DbUtils.getWidget(context);
        componentProvider.setText(ResourceTable.Id_widget_layout_title, "" + userSettings.getName());
        componentProvider.setText(ResourceTable.Id_widget_layout_stargazers, "stars: " + userSettings.getStargazersCount() + "");
        componentProvider.setText(ResourceTable.Id_widget_layout_forks, "forks: " + userSettings.getForksCount() + "");
        String avatarUrl = userSettings.getAvatarUrl();
        String pathName = userSettings.getAvatarUrl().substring(userSettings.getAvatarUrl().lastIndexOf("/"), userSettings.getAvatarUrl().length());
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), pathName + ".png");
        if (file.exists()) {
            PixelMap pixelMap = getPixelMapFromResource(file, new ImageSource.DecodingOptions());
            System.out.println("file.exists()-------------------    " + pixelMap);
            componentProvider.setImagePixelMap(ResourceTable.Id_widget_avatar_image_view_1, pixelMap);
        } else {
            if (NetworkApi.isNetworkConnectedInternet(context)) {
                down(avatarUrl);
            }
        }
        return componentProvider;
    }


    private static PixelMap getPixelMapFromResource(File file, ImageSource.DecodingOptions decodingOptions) {
        PixelMap pixelmap;
        try (InputStream drawableInputStream = new FileInputStream(file)) {
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = FORMAT;
            ImageSource imageSource = ImageSource.create(drawableInputStream, sourceOptions);
            pixelmap = imageSource.createPixelmap(decodingOptions);
            return pixelmap;
        } catch (IOException e) {
            e.getMessage();
        }
        return null;
    }

    private static class MyEventHandler extends EventHandler {

        MyEventHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            int eventId = event.eventId;
            if (eventId == 11) {
                // 更新页面
                componentProvider.setImagePixelMap(ResourceTable.Id_widget_avatar_image_view_1, (PixelMap) event.object);
            }
        }
    }

    private static void down(String url) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("下载失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody responseBody = null;
                BufferedInputStream bis = null;
                FileOutputStream fos = null;
                try {
                    if (call.isCanceled()) {
                        System.out.println("下载失败");
                        return;
                    }
                    if (response.isSuccessful()) {
                        System.out.println("开始下载");
                        responseBody = response.body();
                        long total = responseBody.contentLength();
                        bis = new BufferedInputStream(responseBody.byteStream());
                        String fileName = url.substring(url.lastIndexOf("/"), url.length());
                        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName + ".png");
                        fos = new FileOutputStream(file);
                        byte[] bytes = new byte[1024 * 8];
                        int len;
                        long current = 0;

                        while ((len = bis.read(bytes)) != -1) {
                            fos.write(bytes, 0, len);
                            fos.flush();
                            int progress = (int) (100 * current / total);
                            System.out.println("当前进度是：  " + progress + "%");
                            current += len;
                        }
                        PixelMap pixelMap = getPixelMapFromResource(file, new ImageSource.DecodingOptions());
                        InnerEvent innerEvent = InnerEvent.get();
                        innerEvent.eventId = 11;
                        innerEvent.object = pixelMap;
                        MyEventHandler myEventHandler = new MyEventHandler(EventRunner.getMainEventRunner());
                        myEventHandler.sendEvent(innerEvent);
                    }
                } catch (Exception ignored) {

                } finally {
                    if (null != responseBody) {
                        responseBody.close();
                    }
                    System.out.println("下载完成");
                    assert bis != null;
                    bis.close();
                    assert fos != null;
                    fos.close();
                }
            }
        });
    }
}
